﻿// Screenshotz
//
// Copyright © Frank Nagl, 2008-2012
// admin@franknagl.de
// www.franknagl.de
//
namespace Screenshotz
{
    using System;
    using System.Windows.Forms;
    using Nail;
    using SBIP.Forms;
    using System.IO;

    partial class ImageCutForm
    {
        #region Closing-, Load- and VisibleChanged events

        private void ClosingEvent(
                    object pSender, FormClosingEventArgs pFormClosingEventArgs)
        {
            // removing temporarly stored Clipboard original image, was ..
            //.. stored in ImageCutFormVisibleChanged(..)
            try
            {
                finalImage.Dispose();
                finalImage = null;
                File.Delete(pathToTmpOriginalImage);
            }
// ReSharper disable EmptyGeneralCatchClause
            catch(Exception)
// ReSharper restore EmptyGeneralCatchClause
            {
                // Console.WriteLine(e.Message);
            }

            if (!IsExit)
            {
                BeginInvoke(new MethodInvoker(HideForm));
                pFormClosingEventArgs.Cancel = true;
            }
            else
            {
                mNotifyIcon.Visible = false;
            }
        }

        private void ImageCutFormVisibleChanged(object sender, EventArgs e)
        {
            //Disable the first run after program start
            if (isProgramStart)
            {
                // start hook (bug fix: since 2.20, Hook bug fix)
                hookId = SetHook(Proc);
                isProgramStart = false;
                Program.ReduceMemoryUsage();
                return;
            }
            if (Visible)
            {
                // Has to be moved to Program.cs
                ////time(default:400ms) needed, that windows can copy screenshot into the clipboard
                //System.Threading.Thread.Sleep(SleepTime);

                //if (/*Clipboard.ContainsImage()*/ Clipboard.GetImage() != null)
                //{
                CalcWindowSize(40);
                finalImage = imageCut.OriginalPicture;
                pathToTmpOriginalImage = Program.OptionsPath + "TmpOriginalImage.png";
                finalImage.Save(pathToTmpOriginalImage);
                isComboBoxTextChangedEventSetted = true;
                mNotifyIcon.Visible = Convert.ToBoolean(
                            IOFile.ReadByteData(Program.OptionsFile, 5, ';'));
                //}
                //else
                //{
                //    Console.WriteLine("Zwischenablage enthält keine Daten im Bild-Format.");
                //    Visible = false;
                //}
            }
            else
            {
                // reset hook (bug fix: since 2.20, Hook bug fix)
                UnhookWindowsHookEx(hookId);
                hookId = SetHook(Proc);


                if (imageCut != null)
                {
                    Controls.Remove(imageCut);
                    imageCut.Dispose();
                    imageCut = null;
                }
            }
            Program.ReduceMemoryUsage();
        }

        /// <summary>
        /// When the MainForm loads, it will be hidden and the timer starts.
        /// </summary>
        private void LoadEvent(object pSender, EventArgs pEventArgs)
        {
            BeginInvoke(new MethodInvoker(HideForm));
        }        

        #endregion Closing-, Load- and VisibleChanged events

        #region Button- and Balloon click events

        private void ButtonOkClick(object sender, EventArgs e)
        {
            ProcessImage(imageCut.GetCuttedImage());
        }

        private void NotifyIconBalloonTipClick(object sender, EventArgs eventArgs)
        {
            if (!isBallonUpdate)
                return;
            UpdateItemClick(sender, eventArgs);
        }

        private void NotifyIconDoubleClick(object sender, EventArgs e)
        {
            isBallonUpdate = false;
            mNotifyIcon.ShowBalloonTip(0, language.Text[28], language.Text[29], ToolTipIcon.Info);
        }

        #endregion Button- and Balloon click events

        #region ValueChanged events

        private void DownNumericUpDownValueChanged(object sender, EventArgs e)
        {
            Current.Bottom = (int)downNumericUpDown.Value;
            if (imageCut.Focused && !isSettingGuiToCurrentFastcut)
                return;

            if (Current.Bottom + imageCut.TopPosition >
                imageCut.OriginalHeight - imageCut.MinSizeOfImage)
            {
                downNumericUpDown.Value =
                    imageCut.OriginalHeight - imageCut.BottomPosition;
            }
            else
            {
                imageCut.MoveSlider((imageCut.OriginalHeight -
                                    imageCut.BottomPosition) - Current.Bottom,
                                    Slider.Bottom);
            }
        }

        private void LeftNumericUpDownValueChanged(object sender, EventArgs e)
        {
            Current.Left = (int)leftNumericUpDown.Value;
            if (imageCut.Focused && !isSettingGuiToCurrentFastcut)
                return;

            if (imageCut.RightPosition - Current.Left < imageCut.MinSizeOfImage)
            {
                leftNumericUpDown.Value = imageCut.LeftPosition;
            }
            else
            {
                imageCut.MoveSlider(Current.Left - imageCut.LeftPosition,
                                    Slider.Left);
            }
        }

        private void RightNumericUpDownValueChanged(object sender, EventArgs e)
        {
            Current.Right = (int)rightNumericUpDown.Value;
            if (imageCut.Focused && !isSettingGuiToCurrentFastcut)
                return;

            if (Current.Right + imageCut.LeftPosition >
                imageCut.OriginalWidth - imageCut.MinSizeOfImage)
            {
                rightNumericUpDown.Value =
                    imageCut.OriginalWidth - imageCut.RightPosition;
            }
            else
            {
                imageCut.MoveSlider((imageCut.OriginalWidth -
                                    imageCut.RightPosition) - Current.Right,
                                    Slider.Right);
            }
        }

        private void RotationNumericUpDownValueChanged(object sender, EventArgs e)
        {
            // return, when value not changed 
            // ..(e.g. by KeyUp-event with Tab or cursor key)
            if (Current.Rotation == RotationNumericUpDown.Value)         
                return;

            Current.Rotation = (int)RotationNumericUpDown.Value;
            if (Current.Rotation < 0)
            {
                Current.Rotation += 3600;
            }

            // Original angle
            if (Current.Rotation == 0 || Current.Rotation == 3600)
            {
                ProcessImage(NewBitmapFromPath());
            }
            else
            {
                RotateBilinear filter = new RotateBilinear(
                                    (3600 - Current.Rotation) / 10.0, false);
                ProcessImage(filter.Apply(NewBitmapFromPath()));
            }
        }

        private void UpNumericUpDownValueChanged(object sender, EventArgs e)
        {
            Current.Top = (int)upNumericUpDown.Value;
            if (imageCut.Focused && !isSettingGuiToCurrentFastcut)
                return;

            if (imageCut.BottomPosition - Current.Top < imageCut.MinSizeOfImage)
            {
                upNumericUpDown.Value = imageCut.TopPosition;
            }
            else
            {
                imageCut.MoveSlider(Current.Top - imageCut.TopPosition,
                                    Slider.Top);
            }
        } 

        #endregion ValueChanged events

        #region KeyUp events

        private void DownNumericUpDownKeyUp(object sender, KeyEventArgs e)
        {
            DownNumericUpDownValueChanged(sender, e);

            //Sets the focus to the ImageCut-Control, 
            //..otherwise the key navigation would not work
            if (e.KeyCode == Keys.Return)
                imageCut.Focus();
        }

        private void LeftNumericUpDownKeyUp(object sender, KeyEventArgs e)
        {
            LeftNumericUpDownValueChanged(sender, e);

            //Sets the focus to the ImageCut-Control, 
            //..otherwise the key navigation would not work
            if (e.KeyCode == Keys.Return)
                imageCut.Focus();
        }

        private void RightNumericUpDownKeyUp(object sender, KeyEventArgs e)
        {
            RightNumericUpDownValueChanged(sender, e);

            //Sets the focus to the ImageCut-Control, 
            //..otherwise the key navigation would not work
            if (e.KeyCode == Keys.Return)
                imageCut.Focus();
        }

        private void RotationNumericUpDownKeyUp(object sender, KeyEventArgs e)
        {
            RotationNumericUpDownValueChanged(sender, e);

            //Sets the focus to the ImageCut-Control, 
            //..otherwise the key navigation would not work
            if (e.KeyCode == Keys.Return)
                imageCut.Focus();
        }

        private void UpNumericUpDownKeyUp(object sender, KeyEventArgs e)
        {
            UpNumericUpDownValueChanged(sender, e);

            //Sets the focus to the ImageCut-Control, 
            //..otherwise the key navigation would not work
            if (e.KeyCode == Keys.Return)
                imageCut.Focus();
        }

        #endregion KeyUp events

        #region Text-, Index-, CheckedChanged events

        private void ComboBoxLineStrengthTextChanged(object sender, EventArgs e)
        {
            byte strength;
            if (!byte.TryParse(mComboBox_LineStrength.Text, out strength) || strength > 7)
            {
                strength = 3;
                mComboBox_LineStrength.Text = @"3";
            }
            if (isComboBoxTextChangedEventSetted)
            {
                string tText = "LineStrength;" + mComboBox_LineStrength.Text;
                IOFile.WriteLine(Program.OptionsFile, 4, tText, true);
                //mbutton_OK_Click(null, null);
                imageCut.LineStrength = strength;
                imageCut.Refresh();
            }
        }

        private void ComboBoxRatioSelectedIndexChanged(object sender, EventArgs e)
        {
            if (mComboBox_ratio.Text == language.Text[12])
            {
                imageCut.Ratio = 0.0f;
                mRadioButton_landscapeFormat.Enabled = false;
                mRadioButton_panelFormat.Enabled = false;
                return;
            }

            mRadioButton_landscapeFormat.Enabled = true;
            mRadioButton_panelFormat.Enabled = true;
            string tData = mComboBox_ratio.Text;
            float tNumber1 = float.Parse(tData.Substring(0, tData.IndexOf(' ')));
            float tNumber2 = float.Parse(
                tData.Substring(tData.LastIndexOf(' '),
                                    tData.Length - tData.LastIndexOf(' ')));
            if (isLandScapeFormat)
                imageCut.Ratio = tNumber1 / tNumber2;
            else
                imageCut.Ratio = tNumber2 / tNumber1;

            //Trick to get the ratio handling
            imageCut.MoveSlider(0, Slider.Left);
        }

        private void RadioButtonLandscapeFormatCheckedChanged(object sender, EventArgs e)
        {
            isLandScapeFormat = !isLandScapeFormat;
            ComboBoxRatioSelectedIndexChanged(sender, e);
        }

        #endregion Text-, Index-, CheckedChanged events
    }
}
